package com.cgt.springboot.service.impl;

import com.cgt.springboot.constant.RedisConstants;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.cgt.springboot.mapper.AdminMapper;
import com.cgt.springboot.pojo.Admin;
import com.cgt.springboot.pojo.query.AdminQuery;
import com.cgt.springboot.service.IAdminService;
import com.cgt.springboot.util.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
// <bean name="adminServiceImpl" class="com.situ.springboot.service.impl.AdminServiceImpl">
@Transactional
@Service
public class AdminServiceImpl implements IAdminService {
	private static final Logger logger = LoggerFactory.getLogger(AdminServiceImpl.class);
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private AdminMapper adminMapper;

	@Override
	public List<Admin> selectAll() {
		return adminMapper.selectAll();
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	@Override
	public PageResult<Admin> selectByPage(AdminQuery adminQuery) {
		//记录开始时间 millisecond
		//long begin = System.currentTimeMillis();

		//开启分页
		PageHelper.startPage(adminQuery.getPage(), adminQuery.getLimit());
		//开启分页插件之后 LIMIT offset,pageSiz
		List<Admin> list = adminMapper.selectByPage(adminQuery);
		//查找总的数量PageHelper会自动帮我们完成
		//int totalCount = adminMapper.selectTotalCount(adminMapper);
		PageInfo pageInfo = new PageInfo(list);
		int totalCount = (int) pageInfo.getTotal();

		//模拟一个耗时操作
        /*try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/

        /*long end = System.currentTimeMillis();
        long takeTime = end - begin;
        if (takeTime >= 3000) {
            logger.error("===========执行结束，耗时{}毫秒===============", takeTime);
        } else if (takeTime >= 2000) {
            logger.warn("===========执行结束，耗时{}毫秒===============", takeTime);
        } else {
            logger.info("===========执行结束，耗时{}毫秒===============", takeTime);
        }*/

		return new PageResult<>(0, "", totalCount, list);


	}

	@Override
	public void add(Admin admin) {
		//将保存到数据库的图片放到redis的set集合中
		redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, admin.getImage());
		adminMapper.add(admin);
	}

	@Override
	public Admin login(String name, String password) {
		return adminMapper.login(name, password);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void updateStatus(Integer id, Integer status) {
		adminMapper.updateStatus(id, status);
	}
}
